package com.example.demo.modules.test.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.util.ExcelUtil;
import com.example.demo.common.util.ResultUtil;
import com.example.demo.common.util.entity.ExcelConfig;
import com.example.demo.common.util.entity.Result;
import com.example.demo.common.util.entity.ResultEnum;
import com.example.demo.config.Methods;
import com.example.demo.modules.sys.entity.Dict;
import com.example.demo.modules.sys.service.IDictService;
import com.example.demo.modules.test.dto.student.*;
import com.example.demo.modules.test.entity.Class;
import com.example.demo.modules.test.entity.Student;
import com.example.demo.modules.test.dao.StudentMapper;
import com.example.demo.modules.test.service.IClassService;
import com.example.demo.modules.test.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lmy
 * @since 2022-12-28
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Resource
    private Methods methods;

    @Resource
    private IDictService iDictService;

    @Resource
    private IClassService iClassService;

    @Override
    public IPage<StudentDTO> listStudent(Page page, StudentQueryDTO queryDTO) {
        return this.baseMapper.listStudent(page, queryDTO);
    }

    @Override
    public ResultEnum importStudent(String filePath) {
        String root = methods.getUserDir();
        File importFile = new File(root + File.separator + filePath);
        List<StudentImportDTO> list = ExcelUtil.read(importFile.getPath(), StudentImportDTO.class, new ExcelConfig(null, 2));
        List<Student> insertList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)) {
            for (StudentImportDTO importDTO : list) {
                Student student = new Student();
                QueryWrapper<Class> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Class::getClassNo, importDTO.getClassNo());
                Class cla = iClassService.getOne(queryWrapper);
                BeanUtils.copyProperties(importDTO, student);
                if(Objects.nonNull(cla)) {
                    student.setClassId(cla.getId());
                }
                /**性别字典*/
                QueryWrapper<Dict> sexWrapper = new QueryWrapper<>();
                sexWrapper.lambda().eq(Dict::getType, "sex");
                List<Dict> sexList = iDictService.list(sexWrapper);
                Map<String, String> sexMap = sexList.stream().collect(Collectors.toMap(Dict::getName, Dict::getValue));
                student.setSex(sexMap.getOrDefault(importDTO.getSex(), ""));
                insertList.add(student);
            }
        }
        this.saveBatch(insertList);
        return ResultEnum.SUCCESS;
    }

    @Override
    public Result exportStudent(StudentQueryDTO queryDTO) {
        List<StudentExportDTO> exportDTOS = this.baseMapper.exportStudent(queryDTO);
        /**性别字典*/
        QueryWrapper<Dict> sexWrapper = new QueryWrapper<>();
        sexWrapper.lambda().eq(Dict::getType, "sex");
        List<Dict> sexList = iDictService.list(sexWrapper);
        Map<String, String> sexMap = sexList.stream().collect(Collectors.toMap(Dict::getValue, Dict::getName));
        if(CollectionUtils.isNotEmpty(exportDTOS)) {
            exportDTOS.forEach(e->{
                e.setSex(sexMap.getOrDefault(e.getSex(), ""));
            });
        }
        String timeStamp = String.valueOf(System.currentTimeMillis());
        File exportFile = new File(methods.getUploadPath() + File.separator + timeStamp);
        if(!exportFile.exists()){
            exportFile.mkdirs();
        }
        String path = exportFile.getPath() + File.separator + "学生数据导出.xlsx";
        ExcelUtil.write(path, StudentExportDTO.class, new ExcelConfig(null, 2), exportDTOS);
        return ResultUtil.success(File.separator + "upload" + File.separator + timeStamp + File.separator + "学生数据导出.xlsx");
    }
}
